package com.eazyshop.search.service.imp;

import com.alibaba.fastjson.JSON;
import com.eazyshop.goods.feign.SkuFeign;
import com.eazyshop.search.pojo.SkuInfo;
import com.eazyshop.search.service.SearchService;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.index.query.*;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.Aggregation;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.bucket.terms.StringTerms;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.core.SearchResultMapper;
import org.springframework.data.elasticsearch.core.aggregation.AggregatedPage;
import org.springframework.data.elasticsearch.core.aggregation.impl.AggregatedPageImpl;
import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class SearchServiceImpl implements SearchService {

    @Autowired
    private ElasticsearchTemplate elasticsearchTemplate;


    @Override
    public Map querySkuInfoByQueryMap(Map<String, String> queryMap) {

        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        // 定义返回数据的map
        HashMap<String, Object> resultMap = new HashMap<>();
        // 设置关键字查询条件
        if(!StringUtils.isEmpty(queryMap.get("keywords"))) {

            MatchQueryBuilder matchQueryBuilder = QueryBuilders.matchQuery("name", queryMap.get("keywords")).operator(Operator.AND);

            boolQueryBuilder.must(matchQueryBuilder);

        }

        // 按照品牌进行过滤查询

        if(!StringUtils.isEmpty(queryMap.get("brandName"))){

            TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("brandName", queryMap.get("brandName"));

            boolQueryBuilder.filter(termQueryBuilder);

        }



            NativeSearchQueryBuilder nativeSearchQueryBuilder = new NativeSearchQueryBuilder();
            nativeSearchQueryBuilder.withQuery(boolQueryBuilder);

            // 按照品牌进行聚合查询，设置分组的组名
             String skuBrand="skuBrand";

            // 添加聚合
        /**
         * terms 设置分组的组名
         * field 设置分组查询的字段
         */
        nativeSearchQueryBuilder.addAggregation(AggregationBuilders.terms(skuBrand).field("brandName"));
        // TODO 添加另外一个分组查询
        nativeSearchQueryBuilder.addAggregation(AggregationBuilders.terms(skuBrand).field(""));
        NativeSearchQuery build = nativeSearchQueryBuilder.build();



            AggregatedPage<SkuInfo> skuInfos = elasticsearchTemplate.queryForPage(build, SkuInfo.class, new SearchResultMapper() {
                @Override
                public <T> AggregatedPage<T> mapResults(SearchResponse response, Class<T> clazz, Pageable pageable) {
                    ArrayList<T> list = new ArrayList<>();
                    SearchHits hits = response.getHits();
                    if(hits!=null){
                        for (SearchHit hit : hits) {
                            // 把命中对象转换为SkuInfo
                            SkuInfo skuInfo = JSON.parseObject(hit.getSourceAsString(), SkuInfo.class);
                            list.add((T) skuInfo);
                        }
                    }

                    return new AggregatedPageImpl<T>(list, pageable, hits.getTotalHits(), response.getAggregations());
                }
            });
            // 获得总条数
            int totalPages = skuInfos.getTotalPages();
            resultMap.put("totalPages",totalPages);

            // 获得查询结果条数
            long totalElements = skuInfos.getTotalElements();

            resultMap.put("totalElements",totalElements);

            List<SkuInfo> content = skuInfos.getContent();

            resultMap.put("content",content);

            // 封装品牌的聚合查询结果

            StringTerms aggregation =(StringTerms) skuInfos.getAggregation(skuBrand);// skuBrand分组的组名

        List<String> collect = aggregation.getBuckets().stream().map(s -> s.getKeyAsString()).collect(Collectors.toList());

        resultMap.put("skuBrand",collect);
        return resultMap;
    }
}
